package com.xpalive.config.filter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChangeBodyInputStream extends ServletInputStream {

    private final ByteArrayInputStream bais;

    private static final int FLAG_READY = 1;
    private static final int FLAG_CLOSED = 1 << 1;
    private static final int FLAG_FINISHED = 1 << 2;
    private static final int FLAG_ON_DATA_READ_CALLED = 1 << 3;
    private static final int FLAG_CALL_ON_ALL_DATA_READ = 1 << 4;
    private static final int FLAG_BEING_INVOKED_IN_IO_THREAD = 1 << 5;
    private static final int FLAG_IS_READY_CALLED = 1 << 6;
    private volatile int state;

    public ChangeBodyInputStream(ByteArrayInputStream bais) {
        this.bais = bais;
        this.state = FLAG_READY;
    }

    @Override
    public int read() throws IOException {
        int pos = this.bais.read();
        if (pos == -1) {
            state = FLAG_FINISHED;
        }
        return pos;
    }

    @Override
    public boolean isFinished() {
        return assertState(this.state, FLAG_FINISHED);
    }

    @Override
    public boolean isReady() {
        return assertState(this.state, FLAG_READY) && !this.isFinished();
    }

    @Override
    public void setReadListener(ReadListener readListener) {

    }

    public boolean assertState(int state, int flag) {
        return (state & flag) != 0;
    }
}
